package servlet;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.catalina.tribes.group.interceptors.TwoPhaseCommitInterceptor.MapEntry;

import dao.book.imp.BookDaoImp;
import dao.recording.imp.RecordingDaoImp;
import pojo.Book;
import pojo.Recording;
import util.UUIDrandom;

/**
 * Servlet implementation class SaveRecordingServlet
 */
public class SaveRecordingServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SaveRecordingServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		HttpSession sen = request.getSession();
		Set<Entry<Book, Integer>> set = (Set<Entry<Book, Integer>>) sen.getAttribute("bookset");
		String userId =(String) sen.getAttribute("uid");
		RecordingDaoImp rdi = new RecordingDaoImp();
		if(set!=null){
			for(Entry<Book, Integer> map:set){
				int i= map.getValue();
				if(i==0){}
				else {
					for(int j=i;j>0;j--){
						Recording recording = new Recording(UUIDrandom.idRandom(), userId, map.getKey().getId(), new Date());
						rdi.addRecording(recording);
					}
				}
			}
			for (Map.Entry<Book, Integer> entry : ShoppingCartServlet.bookmap.entrySet()) {
				entry.setValue(0);
			}
			sen.setAttribute("prompt", "购买成功！！");
		}else {
			sen.setAttribute("prompt", "购物车空空如也了！！");
		}
		sen.setAttribute("bookset",null);
		response.sendRedirect("../shoppingcart.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
